import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../../entities/user.entity'
import { Article } from 'src/entities/article.entity';
import { ArticleCollect } from 'src/entities/articleCollect.entity';


@Injectable()
export class ArticleCollectService {
    constructor(
        @InjectRepository(User)
        private readonly userRepository: Repository<User>,
        @InjectRepository(Article)
        private readonly articleRepository: Repository<Article>,
        @InjectRepository(ArticleCollect)
        private readonly articleCollectRepository: Repository<ArticleCollect>,
    ) { }

    async create(userId: string, article_id: string) {


        const article = await this.articleRepository.findOne({ where: { article_id } });

        if (!article) {
            throw new HttpException('文章不存在', HttpStatus.BAD_REQUEST);
        }

        let articleCollect = await this.articleCollectRepository.findOne({
            where: {
                user: {
                    id: userId,
                },
                article: {
                    article_id
                }
            }
        });

        if (articleCollect) return

        articleCollect = await this.articleCollectRepository.save({
            user: await this.userRepository.findOne({ where: { id: userId } }),
            article
        })

        return articleCollect

    }

    async delete(userId: string, article_id: string) {


        await this.articleCollectRepository.delete({
            user: {
                id: userId
            },
            article: {
                article_id
            }
        })


    }
}
